package top.eggcode.control;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import top.eggcode.model.App;
import top.eggcode.model.AppForm;
import top.eggcode.model.AppQuery;
import top.eggcode.model.AppView;
import top.eggcode.service.AppService;
import top.eggcode.store.AppStore;
import top.eggcode.common.lang.BeanUnit;
import top.eggcode.common.mvc.Result;
import top.eggcode.common.mvc.ResultWrapper;
import top.eggcode.component.dict.Translate;
import top.eggcode.component.query.model.PageList;
import top.eggcode.base.PackBaseController;

import javax.annotation.Resource;

@Api(tags = "应用管理")
@RequestMapping("/api/arm/apps")
@RestController
public class AppController extends PackBaseController {

    @Resource
    private AppStore appStore;

    @Resource
    private AppService appService;

    /**
     * 配置
     * 监控方式、网络延迟等
     *
     * @return
     */
    @GetMapping("/config")
    public Result<?> config() {

        return ResultWrapper.successful();
    }

    /**
     * 配置
     * 监控方式、网络延迟等
     *
     * @return
     */
    @PostMapping("/create")
    public Result<?> add(@RequestBody AppForm form) {

        App app = BeanUnit.transfer(form, App.class);
        if (form.getMode() == 2) {
            app.setParams(JSON.toJSONString(form.getHttpConf()));
        } else if (form.getMode() == 3) {
            app.setParams(JSON.toJSONString(form.getSocketConf()));
        }
        app.markCreated();
        appService.put(app);
        return ResultWrapper.successful();
    }

    @PostMapping("/all")
    public Result<?> add() {

        return ResultWrapper.successful();
    }

    @PostMapping("/details")
    public Result<?> detail(@PathVariable String id) {

        return ResultWrapper.successful(appStore.getOne(id));
    }


    @Translate
    @PostMapping("/search_list")
    public Result<?> searchList(@RequestBody AppQuery query) {
        PageList<AppView> page = appStore.searchList(query);

        return ResultWrapper.successful(page);
    }

    @PostMapping("/modify")
    public Result<?> modify(@RequestBody AppForm form) {

        App app = BeanUnit.transfer(form, App.class);
        if (form.getMode() == 2) {
            app.setParams(JSON.toJSONString(form.getHttpConf()));
        } else if (form.getMode() == 3) {
            app.setParams(JSON.toJSONString(form.getSocketConf()));
        }
        app.markUpdated();
        appService.put(app);
        return ResultWrapper.successful();
    }

    @PostMapping("/delete")
    public Result<?> delete(@RequestParam String id) {
        App app = appStore.getOne(id);
        app.markDeleted();
        appStore.save(app);
        return ResultWrapper.successful();
    }
}
